package com.iweipan.activity;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.google.gson.Gson;
import com.iweipan.R;
import com.iweipan.base.WPBaseActivity;
import com.iweipan.bean.CityList;
import com.iweipan.utils.snackbar.SnackbarUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;

import static com.iweipan.R.id.bank_num;
import static com.iweipan.R.id.bank_where;
import static com.iweipan.base.WPUrlBase.WP_CARD_BIND;
import static com.iweipan.base.WPUrlBase.WP_REWT_DO;
import static com.iweipan.base.WPUrlBase.WP_SENDCODE;

/**
 * Created by Administrator on 2016/12/6.
 */

public class GetMoneyActivity extends WPBaseActivity implements OptionsPickerView.OnOptionsSelectListener {
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.text)
    TextView text;
    @BindView(R.id.title_re)
    RelativeLayout titleRe;
    @BindView(R.id.lay_out)
    LinearLayout layOut;
    @BindView(R.id.money_num)
    EditText moneyNum;
    @BindView(R.id.bank)
    TextView bank;
    @BindView(R.id.province)
    TextView province;
    @BindView(R.id.city)
    TextView city;
    @BindView(bank_where)
    EditText bankWhere;
    @BindView(bank_num)
    EditText bankNum;
    @BindView(R.id.bank_name)
    EditText bankName;
    @BindView(R.id.get_btn)
    TextView getBtn;
    @BindView(R.id.my_money)
    TextView myMoney;
    @BindView(R.id.code)
    EditText code;
    @BindView(R.id.sendCode)
    TextView sendCode;
    @BindView(R.id.mobile)
    TextView mobile;
    private String myMoneyNum;
    private String token;
    private String cityJson = null;
    private OptionsPickerView optionsPickerView;
    private OptionsPickerView bankPickerView;
    private ArrayList<String> provinceS;
    private ArrayList<ArrayList<String>> cityS;
    private ArrayList<String> banksArr = new ArrayList<>();
    private boolean isBank;
    private String[] banks = {"工商银行", "建设银行", "中国银行", "中国农业银行", "交通银行", "招商银行", "中国邮政储蓄银行", "光大银行", "广发银行", "中信银行", "兴业银行", "华夏银行", "渣打银行", "花旗银行"};
    private String mobileString;

    @Override
    public int bindLayout() {
        return R.layout.activity_getmoney;
    }

    @Override
    public void initToolbarColor() {
        color = getResources().getColor(R.color.actionbar_title_bg);
        statusBarAlpha = 60;
    }

    @Override
    public void initView(View view) {
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        Intent intent = getIntent();
        myMoneyNum = intent.getStringExtra("myMoney");
        token = intent.getStringExtra("token");
        mobileString = intent.getStringExtra("mobile");
        optionsPickerView = new OptionsPickerView(this);
        bankPickerView = new OptionsPickerView(this);
        mobile.setText("手机号码:" + mobileString);
    }

    @Override
    public void doBusiness(Context mContext) {
        myMoney.setText(myMoneyNum);
        for (String s : banks) {
            banksArr.add(s);
        }
        bankPickerView.setPicker(banksArr);
        bankPickerView.setCyclic(false);
        bankPickerView.setOnoptionsSelectListener(this);

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("token", token);
            jsonObject.put("type", "2");
            OkHttpUtils.get()
                    .url(WP_CARD_BIND)
                    .addParams("p", jsonObject.toString())
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {

                        }

                        @Override
                        public void onResponse(String response, int id) {
                            Log.e("GetMoneyActivity", response);
                            try {
                                JSONObject cardBind = new JSONObject(response);
                                String code = cardBind.getString("code");
                                if (code.equals("200")) {
                                    JSONObject result = cardBind.getJSONObject("result");
                                    String cardNum = result.getString("cardNum");
                                    if (cardNum.length() == 1) {
                                        return;
                                    }
                                    bankNum.setText(cardNum);
                                    bankNum.setEnabled(false);


                                    String cardName = result.getString("cardName");
                                    String subBranch = result.getString("subBranch");
                                    String cityS = result.getString("city");
                                    city.setText(cityS);
                                    bankWhere.setText(subBranch);
                                    bankName.setText(cardName);

                                    city.setEnabled(false);
                                    bankName.setEnabled(false);
                                    bankWhere.setEnabled(false);

                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        }
                    });
        } catch (JSONException e) {
            e.printStackTrace();
        }


        initJsonData();

    }

    private void initJsonData() {
        try {
            StringBuffer stringBuffer = new StringBuffer();
            InputStream open = getAssets().open("city.json");
            byte[] bytes = new byte[open.available()];
            int len = -1;
            while ((len = open.read(bytes)) != -1) {
                stringBuffer.append(new String(bytes, 0, len, "utf-8"));
            }
            open.close();
            cityJson = stringBuffer.toString();
            Gson gson = new Gson();
            CityList cityList = gson.fromJson(cityJson, CityList.class);
            ArrayList<CityList.CitylistBean> citylist = (ArrayList<CityList.CitylistBean>) cityList.getCitylist();
            provinceS = new ArrayList<>();
            cityS = new ArrayList<>();

            for (CityList.CitylistBean citylistBean : citylist) {
                String p = citylistBean.getP();
                List<CityList.CitylistBean.CBean> c = citylistBean.getC();
                ArrayList<String> nS = new ArrayList<>();
                for (CityList.CitylistBean.CBean cBean : c) {
                    String n = cBean.getN();
                    nS.add(n);
                }
                cityS.add(nS);
                provinceS.add(p);
            }
            optionsPickerView.setPicker(provinceS, cityS, true);
            optionsPickerView.setCyclic(false);
            optionsPickerView.setOnoptionsSelectListener(this);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void resume() {

    }

    @Override
    public void destroy() {

    }


    @OnClick({R.id.bank, R.id.province, R.id.city, R.id.get_btn, R.id.sendCode})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bank:
                isBank = true;
                if (!bankPickerView.isShowing()) {
                    bankPickerView.show();
                }

                break;
            case R.id.province:
                isBank = false;
                if (!optionsPickerView.isShowing()) {
                    optionsPickerView.show();
                }

                break;
            case R.id.city:
                isBank = false;
                if (!optionsPickerView.isShowing()) {
                    optionsPickerView.show();
                }
                break;
            case R.id.get_btn:
                initHttpGet();
                break;
            case R.id.sendCode:

                initHttpSendCode();
                break;
        }
    }

    private void initHttpSendCode() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("me", mobileString);
            jsonObject.put("mid", "016");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        OkHttpUtils.get()
                .url(WP_SENDCODE)
                .addParams("p", jsonObject.toString())
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        try {
                            JSONObject result = new JSONObject(response);
                            String code = result.getString("code");
                            if (code.equals("200")) {
                                changeBtnGetCode();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                });
    }


    private boolean isSendCode = true;
    private int codeTime = 60;

    private void changeBtnGetCode() {
        Thread thread = new Thread() {
            @Override
            public void run() {
                if (isSendCode) {
                    while (codeTime > 0) {
                        codeTime--;
                        if (GetMoneyActivity.this == null) {
                            break;
                        }

                        GetMoneyActivity.this
                                .runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        sendCode.setText("获取验证码("
                                                + codeTime + ")");
                                        sendCode
                                                .setClickable(false);
                                    }
                                });
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    isSendCode = false;
                }
                codeTime = 60;
                isSendCode = true;
                if (GetMoneyActivity.this != null) {
                    GetMoneyActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            sendCode.setText("获取验证码");
                            sendCode.setClickable(true);
                        }
                    });
                }
            }

            ;
        };
        thread.start();
    }


    private void initHttpGet() {
        if (moneyNum.getText().toString().length() == 0) {
            SnackbarUtil.shortMake(moneyNum, "请输入提现金额").show();
            return;
        } else if (Double.parseDouble(moneyNum.getText().toString()) * 100 * 1.0 <= 200) {
            SnackbarUtil.shortMake(moneyNum, "提现金额应在2元至5000元").show();
        }
        if (bankWhere.getText().toString().length() == 0) {
            SnackbarUtil.shortMake(moneyNum, "请输入开户支行").show();
            return;
        }
        if (bankNum.getText().toString().length() == 0) {
            SnackbarUtil.shortMake(moneyNum, "请输入银行卡号").show();
            return;
        }
        if (bankName.getText().toString().length() == 0) {
            SnackbarUtil.shortMake(moneyNum, "请输入持卡人姓名").show();
            return;
        }

        if (bank.getText().toString().equals("请选择银行")) {
            SnackbarUtil.shortMake(moneyNum, "请选择银行").show();
            return;
        }
        if (province.getText().toString().equals("省份")) {
            SnackbarUtil.shortMake(moneyNum, "请选择省份").show();
            return;
        }
        if (city.getText().toString().equals("城市")) {
            SnackbarUtil.shortMake(moneyNum, "请选择城市").show();
            return;
        }
        String codeString = code.getText().toString();
        String cardNo = bankNum.getText().toString();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("token", token);
            jsonObject.put("txMoney", Double.parseDouble(moneyNum.getText().toString()) * 100);
            jsonObject.put("bank", bank.getText().toString());
            jsonObject.put("subBank", bankWhere.getText().toString());
            jsonObject.put("cardNo", cardNo);
            jsonObject.put("account", bankName.getText().toString());
            jsonObject.put("province", province.getText().toString());
            String md5 = MoneyActivity.md5(cardNo + codeString);
            jsonObject.put("city", city.getText().toString());
            jsonObject.put("code", md5);
            jsonObject.put("notifyUrl", "http://o.com");

        } catch (JSONException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        OkHttpUtils.get()
                .url(WP_REWT_DO)
                .addParams("p", jsonObject.toString())
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("GetMoneyActivity", response);
                        SnackbarUtil.shortMake(moneyNum, "提现申请成功,请勿重复提交").show();
                    }
                });


    }

    @Override
    public void onOptionsSelect(int options1, int option2, int options3) {
        if (!isBank) {
            if (provinceS != null && provinceS.size() > 0 && cityS != null && cityS.size() > 0) {
                try {
                    province.setText(provinceS.get(options1));
                    city.setText(cityS.get(options1).get(option2));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else {
            bank.setText(banksArr.get(options1));

        }

    }


}
